package cc.linker.steplink.crm.task;

import cc.linker.steplink.crm.commons.lock.RedisLock;
import cc.linker.steplink.crm.service.OverViewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static cc.linker.steplink.crm.merchanth5.controller.OverViewInfoController.*;

@Slf4j
@Component
public class OverViewStatisticsTask {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private OverViewService overViewService;

    @RedisLock("OverViewStatisticsTask")
    @Scheduled(cron = "2 0 0 * * ?")
//    @Scheduled(cron = "*/10 * * * * ?")
    public void execute() {
        String day = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        Map<String, String> allMap = new HashMap<>(6);
        allMap.put(NEW_SUBSCRIBE, "newSubscribe");
        allMap.put(PAGE_EXPOSURE, "pageExposure");
        allMap.put(GOODS_EXPOSURE, "goodsExposure");
        // 新关注、页面曝光、商品曝光
        allMap.forEach((x, y) -> {
            Map<Object, Object> entries = redisTemplate.opsForHash().entries(x);
            entries.forEach((orgId, num) -> {
                Map<String, Object> map = new HashMap<>(3);
                map.put("orgId", orgId);
                map.put("day", day);
                map.put(y, num);
                overViewService.insertPageExposure(map);
            });
            redisTemplate.delete(x);
        });
        // 访客
        Set<String> keys = redisTemplate.keys(GUEST + "*");
        keys.forEach(x -> {
            String orgId = x.substring(x.length() - 5);
            Map<String, Object> map = new HashMap<>(3);
            map.put("orgId", orgId);
            map.put("day", day);
            Long size = redisTemplate.opsForSet().size(x);
            map.put("guest", size);
            overViewService.insertPageExposure(map);
        });
        redisTemplate.delete(keys);
        // 活跃度
        List<Map<String, Object>> activity = overViewService.statisticalActivityByDay();
        activity.forEach(x -> {
            String activityStr = x.get("activity").toString();
            String s = new BigDecimal(activityStr).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
            x.put("activity", s);
            x.put("day", day);
            overViewService.insertPageExposure(x);
        });
    }
}
